package com.block.datapush.special.utils;

import cn.hutool.core.collection.CollUtil;
import com.block.db.entity.SpecialCostomItemInfo;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;

public class SpecialUtil {

    /**
     * 根据概率获取可以推送的分流任务
     *
     * @param canPushItemList
     * @return
     */
    public static SpecialCostomItemInfo getCanPushItemInfo(List<SpecialCostomItemInfo> canPushItemList){

        if (CollUtil.isEmpty(canPushItemList)){
            return null;
        }

        // 总的概率区间(此处可再优化)
        float totalPro = 0f;
        // 存储每个奖品新的概率区间
        List<Float> proSection = new ArrayList<Float>();
        proSection.add(0f);

        // 遍历每个奖品，设置概率区间，总的概率区间为每个概率区间的总和
        for (SpecialCostomItemInfo itemInfo: canPushItemList) {
            // 每个概率区间为奖品概率乘以1000（把三位小数转换为整）
            totalPro += itemInfo.getPriceAmount().floatValue() * 100;
            proSection.add(totalPro);

        }
        // 获取总的概率区间中的随机数
        SecureRandom random = new SecureRandom();
        float randomPro = (float) random.nextInt((int) totalPro);

        SpecialCostomItemInfo itemInfo = null;
        canPushItemList.remove(itemInfo);
        // 判断取到的随机数在哪个奖品的概率区间中
        for (int i = 0, size = proSection.size(); i < size; i++) {
            if (randomPro >= proSection.get(i) && randomPro < proSection.get(i + 1)) {
                itemInfo =  canPushItemList.get(i);
                break;
            }
        }

        canPushItemList.remove(itemInfo);
        return itemInfo;
    }

}
